// 引入 vk-unicloud
const vkCloud = require('vk-unicloud');
// 通过 vkCloud.createInstance 创建 vk 实例
const vk = vkCloud.createInstance({
	baseDir: __dirname,
	requireFn: require
});

const xlsx = require('./lib/node-xlsx.js');
const fs = require('fs');

const dbName = {
	category: "vk-mall-goods-category", // 商品分类表
	goods: "vk-mall-goods", // 商品表
	sku: "vk-mall-goods-sku", // sku表
};

/**
 * 此为单独的云对象，是因为 node-xlsx 的npm包太大了，不写在router内，需要独立出来
 */
module.exports = {
	_before: function() { // 通用预处理器

	},
	/**
	 * 导入商品
	 */

	async importGoods(data) {
		const cloudInfo = this.getCloudInfo();
		try {
			//console.log('解密前: ', data)
			data = vk.crypto.aes.decrypt({ data });
			//console.log('解密后: ', data)
		} catch (err) {
			return { code: -1, msg: "参数解密错误" };
		}

		let {
			base64, // 文件的base64值
			imageMode, // 图片储存方式
		} = data;

		let index = base64.indexOf("base64,");
		if (index > -1) {
			base64 = base64.substring(index + 7);
		}
		let imageBuffer = Buffer.from(base64, "base64");
		let fileName = `goods.xlsx`;
		let filePath = "";
		if (cloudInfo.provider === "aliyun") {
			// 阿里云
			filePath = `${__dirname}/${fileName}`;
		} else {
			// 腾讯云
			filePath = `/tmp/${fileName}`;
		}
		// 写入文件
		await fs.writeFileSync(filePath, imageBuffer);
		// 解析goods.xlsx
		let rows = await parseXlsx({
			path: filePath, // 文件名
			startRow: 1, // 从第几行开始读取
		});
		//console.log('rows: ', rows)

		// 解析完后删除goods.xlsx
		await fs.unlinkSync(filePath);

		// if (rows.length > 1000) {
		// 	return { code:-1, msg:"一次导入最多1000个商品" };
		// }

		let categorys = await vk.baseDao.select({
			dbName: dbName.category,
			getCount: false,
			getMain: true,
			pageIndex: 1,
			pageSize: -1
		});
		if (rows) {
			// console.log('rows: ', rows)
			//return;

			let goodsList = []; // 需要添加的商品列表
			let skuList = []; // 需要添加的sku列表
			let goodsIds = [];
			for (let i = 0; i < rows.length; i++) {
				let item = rows[i];
				//console.log(`正在处理第${i+1}个商品`,item)
				let goods_id = Date.now() + "-" + vk.pubfn.random(16, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", goodsIds);
				goodsIds.push(goods_id);
				let goods_name = item["商品名称"];
				let category_ids = [];
				if (item["所属分类"]) {
					let arr = item["所属分类"].split(",");
					arr.map((categoryName) => {
						let categoryItem = vk.pubfn.getListItem(categorys, "name", categoryName);
						if (categoryItem && categoryItem._id) {
							category_ids.push(categoryItem._id);
						}
					});
				}
				let goods_banner_imgs = item["商品轮播图链接"] ? item["商品轮播图链接"].split(",") : [];
				let goods_detail_imgs = item["商品轮播图链接"] ? item["商品轮播图链接"].split(",") : [];
				let goods_services = item["服务标签"] ? item["服务标签"].split(",") : [];

				let exp_time_mode = item["虚拟商品有效期模式"] || 0;
				let exp_time_range, exp_time_rule;
				if (exp_time_mode == 1) exp_time_range = item["虚拟商品有效期"] ? item["虚拟商品有效期"].split("-") : [];
				if (exp_time_mode == 2) exp_time_rule = item["虚拟商品有效期"] ? item["虚拟商品有效期"].split("-") : [];

				let spec_list = [];
				if (item["规格信息"]) {
					// 颜色:灰色,白色;内存:256G,512G
					let arr = item["规格信息"].split(";");
					// arr ["颜色:灰色,白色","内存:256G,512G"]
					arr.map((specItem) => {
						// specItem: 颜色:灰色,白色
						let arr2 = specItem.split(":");
						// arr2 ["颜色","灰色,白色"]
						let arr3 = arr2[1].split(",");
						// arr3 ["灰色","白色"]
						let list = arr3.map((arr3Item) => {
							return {
								name: arr3Item
							}
						});
						spec_list.push({
							name: arr2[0],
							list: list
						});
					});
				} else {
					throw new Error(`msg:商品【${goods_name}】规格信息错误`);
				}
				let initial_sell_count = item["商品初始销量"] ? Number(item["商品初始销量"]) : 0;
				let sort = item["排序"] || 0;
				goodsList.push({
					_id: goods_id,
					status: 1,
					sort,
					is_on_sale: item["销售状态"] == "上架" ? true : false,
					type: item["商品类型"] == "虚拟" ? 1 : 0,
					name: goods_name,
					category_ids,
					goods_desc: item["商品描述"],
					goods_thumb: item["商品图片链接"],
					goods_banner_imgs,
					goods_detail_mode: 0,
					goods_detail_imgs,
					goods_services,
					is_free_delivery: item["是否包邮"] == "是" ? true : false,
					freight_id: item["运费id"],
					exp_time_mode: item["虚拟商品有效期模式"],
					exp_time_range,
					exp_time_rule,
					spec_list,
					is_new: item["是否新品"] == "是" ? true : false,
					is_best: item["是否精品"] == "是" ? true : false,
					is_hot: item["是否热销"] == "是" ? true : false,
					disable_vip: item["是否禁用会员价"] == "是" ? true : false,
					disable_coupon: item["是否禁用优惠券"] == "是" ? true : false,
					cart_rule: {
						step: 1, //步进值
						min: 1, //最少起购量
						max: 100000, //单次最大购买数量(0为不限制)
						step_strictly: false //是否只能输入对应的倍数
					},
					limit_buy_rule: {
						activity_limit_num: 0, //活动期间内总限购 0代表不限购
						every_day_limit_num: 0, //常规每日限购 0代表不限购
						limit_time: []
					},
					integral_rule: {
						is_calc: false,
						is_fixed_calc: false,
						proportion_value: "",
						fixed_value: "",
						is_level_k: true
					},
					initial_sell_count,
					real_sell_count: initial_sell_count,
					total_sell_count: initial_sell_count,
					comment_count: 0,
					view_count: 0,
				});

				if (item["具体规格"]) {
					//灰色,256G:8000,0,9999,1,https://vkceyugu.cdn.bspapp.com/VKCEYUGU-cf0c5e69-620c-4f3c-84ab-f4619262939f/43c36bbd-5cfd-4c87-8362-5c3d0fbb7a0d.jpg;灰色,512G:10000,0,9999,1,https://vkceyugu.cdn.bspapp.com/VKCEYUGU-cf0c5e69-620c-4f3c-84ab-f4619262939f/43c36bbd-5cfd-4c87-8362-5c3d0fbb7a0d.jpg;
					let arr = item["具体规格"].split(";");
					arr.map((specItem) => {
						// specItem: 灰色,256G::8000,0,9999,1,图片地址
						let arr2 = specItem.split("::");
						// arr2 ["灰色,256G","8000,0,9999,1,图片地址"]
						let sku_name_arr = arr2[0].split(",");
						// sku_name_arr ["灰色","256G"]
						let sku_name = arr2[0].replace(/,/g, " / ");
						let arr3 = arr2[1].split(",");
						// arr3 [售价,市场价,库存,重量,图片]
						let price = vk.pubfn.toDecimal(Number(arr3[0]) * 100, 0);
						let market_price = vk.pubfn.toDecimal(Number(arr3[1]) * 100, 0);
						let stock = Number(arr3[2]);
						let weight = Number(arr3[3]);
						let image = arr3[4];

						skuList.push({
							goods_id,
							goods_name: goods_name,
							image,
							sku_name,
							sku_name_arr,
							price,
							market_price,
							stock,
							weight,
							real_sell_count: 0
						});
					});
				} else {
					throw new Error(`msg:商品【${goods_name}】具体规格错误`);
				}
			}
			// 将能转数字的字符串转数字（排除手机号，身份证）
			goodsList = vk.pubfn.string2Number(goodsList);
			skuList = vk.pubfn.string2Number(skuList);
			// console.log('goodsList: ', goodsList)
			// console.log('skuList: ', skuList)
			// return;

			// 每次只加1000个商品
			let oneAddNum = 1000;
			// let forNum = Math.floor(goodsList.length / oneAddNum); // 向下取整
			// if (goodsList.length % oneAddNum !== 0) {
			// 	forNum++;
			// }

			let goodsDataList = [];
			let goodsDataIndex = 0;
			for (let i = 0; i < goodsList.length; i++) {
				let item = goodsList[i];
				if (!goodsDataList[goodsDataIndex]) goodsDataList[goodsDataIndex] = [];
				if (goodsDataList[goodsDataIndex].length === oneAddNum) {
					goodsDataIndex++;
					goodsDataList[goodsDataIndex] = [];
				}
				goodsDataList[goodsDataIndex].push(item);
			}

			let skuDataList = [];
			let skuDataIndex = 0;
			for (let i = 0; i < skuList.length; i++) {
				let item = skuList[i];
				if (!skuDataList[skuDataIndex]) skuDataList[skuDataIndex] = [];
				if (skuDataList[skuDataIndex].length === oneAddNum) {
					skuDataIndex++;
					skuDataList[skuDataIndex] = [];
				}
				skuDataList[skuDataIndex].push(item);
			}

			// console.log('goodsDataList: ', goodsDataList)
			// console.log('skuDataList: ', skuDataList)
			// return 1;

			let goodsBatchRunRes = await vk.pubfn.batchRun({
				// 主执行函数
				main: async (item, index) => {
					await vk.baseDao.adds({
						dbName: dbName.goods,
						dataJson: item
					});
				},
				// 最大并发量，如果设置为1，则会按顺序执行
				concurrency: 100,
				// 数据源，这些数据会依次跑一遍main函数
				data: goodsDataList
			});

			let skuBatchRunRes = await vk.pubfn.batchRun({
				// 主执行函数
				main: async (item, index) => {
					await vk.baseDao.adds({
						dbName: dbName.sku,
						dataJson: item
					});
				},
				// 最大并发量，如果设置为1，则会按顺序执行
				concurrency: 100,
				// 数据源，这些数据会依次跑一遍main函数
				data: skuDataList
			});

			console.log('goodsBatchRunRes: ', goodsBatchRunRes)
			console.log('skuBatchRunRes: ', skuBatchRunRes)
		}

		return {
			code: 0,
			msg: `导入成功`
		}

	}

}




async function parseXlsx(obj) {
	let {
		path,
		startRow
	} = obj;
	try {
		let firstTable = [];
		//表数据
		let tableData = xlsx.parse(path);

		firstTable = tableData[0];

		let firstTableData = firstTable.data;
		let rows = [];
		let titleList = firstTableData[startRow - 1];
		for (let index = startRow; index < firstTableData.length; index++) {
			let item = firstTableData[index];
			let row = {};
			titleList.map((titleItem, titleIndex) => {
				row[titleItem] = item[titleIndex];
			});
			rows.push(row);
		}
		return rows;
	} catch (e) {
		//输出日志
		console.log("excel读取异常,error=%s", e.stack);
	}
}
